package com.ctshk.rpc.ship.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.enums.ship.ShipCompanyType;
import com.ctshk.common.enums.ship.ShipErrorCodeEnum;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.ParseXmlUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.order.ship.req.ShipOrderReq;
import com.ctshk.rpc.order.ship.service.IShipOrderService;
import com.ctshk.rpc.ship.dto.*;
import com.ctshk.rpc.ship.entity.*;
import com.ctshk.rpc.ship.mapper.*;
import com.ctshk.rpc.ship.req.ShipZJProductApiReq;
import com.ctshk.rpc.ship.req.ShipZJProductApiSubmitReq;
import com.ctshk.rpc.ship.req.ShipZJProductApiSubmitTicketsReq;
import com.ctshk.rpc.ship.service.ZJShipProductService;
import com.itextpdf.text.DocumentException;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 船票产品 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-03-05
 */
@DubboService
public class ZJShipProductServiceImpl extends ServiceImpl<ShipProductMapper, ShipProduct> implements ZJShipProductService {

    @Value("${ptmsqa.ws.CksServices.accountNoConstant}")
    private String accountNoConstant;

    @Value("${ptmsqa.ws.CksServices.passWordConstant}")
    private String passWordConstant;

    @Value("${ptmsqa.ws.CksServices.workSiteConstant}")
    private String workSiteConstant;

    @Value("${ptmsqa.ws.CksServices.urlConstant}")
    private String urlConstant;

    @Value("${ptmsqa.ws.CksServices.ip}")
    private String IP;

    @DubboReference
    private IShipOrderService iShipOrderService;


    @Autowired
    private ShipProductMapper shipProductMapper;

    @Autowired
    private ShipProductSeatMapper shipProductSeatMapper;

    @Autowired
    private ShipProductCostMapper shipProductCostMapper;

    @Autowired
    private ShipRouteMapper shipRouteMapper;

    @Autowired
    private ShipProductCostDateMapper shipProductCostDateMapper;

    @Autowired
    private ShipProductReservationSettingsMapper shipProductReservationSettingsMapper;

    @Autowired
    private ShipProductCostTouristMapper shipProductCostTouristMapper;

    @Autowired
    private ShipProductChannelOfflineSelfCustomMapper shipProductChannelOfflineSelfCustomMapper;

    @Autowired
    private ShipInitializationSettingsMapper shipInitializationSettingsMapper;


    private static Long CHARGE_USER_ID = 9999L;

    /**
     * 珠江船票请求头 主要用于封装账号密码等信息
     * @param methodXml
     * @return
     */
    public String requestZJInterface(String methodXml) {
        String result = null;
        String account = accountNoConstant;
        String pasword = passWordConstant;
        String worksite = workSiteConstant;
        String url = "\"" + urlConstant + "\"";
        String requestUrl = urlConstant;
        try {
            String timestamp = DateUtil.fmt(LocalDateTime.now(), "yyyyMMddHHmm");
            String pwd = SecureUtil.md5(account + SecureUtil.md5(pasword).toUpperCase() + timestamp).toUpperCase();
            String xml = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                    "    <soap:Header>" +
                    "        <tns:RequestSOAPHeader xmlns:tns=" + url + ">" +
                    "            <tns:account xmlns=" + url + ">" + account + "</tns:account>" +
                    "            <tns:pwd xmlns=" + url + ">" + pwd + "</tns:pwd>" +
                    "            <tns:timestamp xmlns=" + url + ">" + timestamp + "</tns:timestamp>" +
                    "            <tns:worksite xmlns=" + url + ">" + worksite + "</tns:worksite>" +
                    "            <tns:discount_id xmlns=" + url + "/>" +
                    "        </tns:RequestSOAPHeader>" +
                    "    </soap:Header>" +
                    "    <soap:Body>" +
                    methodXml +
                    "    </soap:Body>" +
                    "</soap:Envelope>";
            result = HttpUtil.post(requestUrl, xml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取所有珠江船票在运营的航线信息 用于保存在我们的航线表里面
     * @return
     */
    @Override
    public Map<String, Object> getShippingLine() {
        Map<String, Object> stringObjectMap = null;
        try {
            String s = requestZJInterface("<ns2:getShippingLine xmlns:ns2=\"http://ws.service.gen.cks.com/\"/>");
            stringObjectMap = ParseXmlUtil.parseXml(s);
            Map Envelope = (Map) stringObjectMap.get("Envelope");
            Map Body = (Map) Envelope.get("Body");
            Map getShippingLineResponse = (Map) Body.get("getShippingLineResponse");
            String returnMap = (String) getShippingLineResponse.get("return");
            Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
            Map table = (Map) stringObjectMap1.get("TABLE");
            List<Map<String, String>> rowList = (List) table.get("ROW");
            ShipRoute shipRoute1 = new ShipRoute();
            shipRoute1.setStatus(ShipConstants.INVALID);
            shipRouteMapper.update(shipRoute1, Wrappers.<ShipRoute>lambdaQuery().eq(ShipRoute::getCompanyType, "2"));
            for (Map<String, String> map : rowList) {
                ShipRoute shipRoute = new ShipRoute();
                shipRoute.setId(SnowflakeIdWorker.nextId());
                shipRoute.setRouteCode(map.get("LINECODE")); //航线code
                shipRoute.setDepPlaceCode(map.get("FROMPORTCODE"));//出发code
                shipRoute.setDepPlaceName(map.get("FROMPORTCNAME"));//出发
                shipRoute.setDepPlaceTcName(map.get("FROMPORTTNAME"));//出发繁体
                shipRoute.setDepPlaceEnName(map.get("FROMPORTENAME"));//出发英文
                shipRoute.setArrPlaceCode(map.get("TOPORTCODE"));//到达code
                shipRoute.setArrPlaceName(map.get("TOPORTCNAME"));//到达
                shipRoute.setArrPlaceTcName(map.get("TOPORTTNAME"));//到达繁体
                shipRoute.setArrPlaceEnName(map.get("TOPORTENAME"));//到达英文
                shipRoute.setRealName(Integer.parseInt(map.get("REALNAME")));//是否实名制
                shipRoute.setRouteName(map.get("FROMPORTCNAME") + map.get("TOPORTCNAME"));
                shipRoute.setCompanyType(2L);//船公司类型(1 信德船票，2 珠江船票)
                shipRoute.setCreateId(CHARGE_USER_ID);
                shipRoute.setStatus(ShipConstants.VALID);
                shipRoute.setIsDeleted(ShipConstants.NOT_DELETE);
                shipRoute.setGmtCreate(LocalDateTime.now());
                ShipRoute shipRouteItem = shipRouteMapper.selectOne(
                        new QueryWrapper<ShipRoute>().lambda().eq(ShipRoute::getRouteCode, map.get("LINECODE"))
                                .eq(ShipRoute::getDepPlaceCode, map.get("FROMPORTCODE"))
                                .eq(ShipRoute::getArrPlaceCode, map.get("TOPORTCODE"))
                );
                if (null == shipRouteItem) {
                    shipRouteMapper.insert(shipRoute);
                } else {
                    Long oldId = shipRouteItem.getId();
                    BeanUtils.copyProperties(shipRoute, shipRouteItem);
                    shipRouteItem.setId(oldId);
                    shipRouteItem.setGmtModified(LocalDateTime.now());
                    shipRouteItem.setModifiedId(CHARGE_USER_ID);
                    shipRouteMapper.updateById(shipRouteItem);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringObjectMap;
    }


    /**
     * 根据已获取的珠江船票航线，循环遍历 去请求珠江船票的产品 然后保存在我们产品表里面
     * @return
     */
    @Override
    public Map<String, Object> getVoyage() {
        Map<String, Object> stringObjectMap = null;

        List<ShipRoute> shipRoutes = shipRouteMapper.selectList(
                new QueryWrapper<ShipRoute>().lambda().eq(ShipRoute::getCompanyType, "2")
                        .eq(ShipRoute::getStatus, ShipConstants.VALID)
        );
        //去拿一下api设置
        ShipInitializationSettings shipInitializationSettings = shipInitializationSettingsMapper.selectOne(Wrappers.<ShipInitializationSettings>lambdaQuery());
        for (ShipRoute shipRoute : shipRoutes) {
            try {
                String headXml = "<ns2:getVoyage xmlns:ns2=\"http://ws.service.gen.cks.com/\"> <filterXml>";
                String bodyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<TABLE VERSION=\"1.0\">";
                bodyXml += "<ROW>" +
                        "<SAILDATE>" + LocalDate.now().plusDays(1) + "</SAILDATE>" +
                        "<SAILDATERETURN></SAILDATERETURN>" +
                        "<FROMPORTCODE>" + shipRoute.getDepPlaceCode() + "</FROMPORTCODE>" +
                        "<TOPORTCODE>" + shipRoute.getArrPlaceCode() + "</TOPORTCODE>" +
                        "<FROMPORTCODERETURN></FROMPORTCODERETURN>" +
                        "<TOPORTCODERETURN></TOPORTCODERETURN>" +
                        "<CURRENCYCODE>HKD</CURRENCYCODE>" +
                        "<ISROUNDTRIP>0</ISROUNDTRIP>" +
                        "<LANG>C</LANG>" +
                        "</ROW>";

                bodyXml += "</TABLE>";
                String s1 = StringEscapeUtils.escapeXml(bodyXml);

                String s = requestZJInterface(headXml + s1 + "</filterXml></ns2:getVoyage>");
                stringObjectMap = ParseXmlUtil.parseXml(s);
                Map Envelope = (Map) stringObjectMap.get("Envelope");
                Map Body = (Map) Envelope.get("Body");
                Map getShippingLineResponse = (Map) Body.get("getVoyageResponse");
                String returnMap = (String) getShippingLineResponse.get("return");
                Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
                Map dateSet = (Map) stringObjectMap1.get("DATASET");
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                List<Map<String, Object>> rowList = (List) dateSet.get("VOYAGE");
                for (Map<String, Object> map : rowList) {
                    Map<String, List> dtseatrankprice = (Map<String, List>) map.get("DTSEATRANKPRICE");
                    List<Map<String, String>> rows = dtseatrankprice.get("ROW");
                    //用户ID
                    Long chargeUserId = CHARGE_USER_ID;
                    for (Map<String, String> rowMap : rows) {
                        /**船票保存*/
                        //每日库存
                        int dailyStock = 0;
                        if (null != map.get("TICKETNUM")) {
                            String[] seatrankids = map.get("TICKETNUM").toString().replace("(", ",").split("\\)");
                            for (String seatrankid : seatrankids) {
                                String[] splitStr = seatrankid.split(",");
                                if (splitStr[0].equals(rowMap.get("SEATRANKID"))) {
                                    dailyStock = Integer.parseInt(splitStr[1]);
                                }
                            }
                        }
                        ShipProduct shipProduct = new ShipProduct();
                        Long productId = SnowflakeIdWorker.nextId();
                        shipProduct.setId(productId);
                        shipProduct.setVoyage(null == rowMap.get("VOYAGEROUTEID") ? "" : rowMap.get("VOYAGEROUTEID").toString());
                        shipProduct.setCabinClassStr(rowMap.get("SEATRANKID"));
                        shipProduct.setCode(map.get("SHIPCODE").toString());
                        shipProduct.setShipTypeName(map.get("SHIP").toString());
                        shipProduct.setCompanyType(2L);
                        shipProduct.setStock(dailyStock);
                        shipProduct.setRouteId(shipRoute.getId());
                        shipProduct.setSupplierName("珠江船舶");
                        //产品来源 1.手动 2.api产品
                        shipProduct.setProductSource(2);
                        shipProduct.setDepTime(LocalDateTime.parse(map.get("SETOFFDATE").toString() + " " + map.get("SETOFFTIME").toString(), df));
                        //审批状态（1 待提交，2 待审批，3 审批中，4 审批不通过，5 审批通过）
                        shipProduct.setApprovalStatus(ShipConstants.REJECTED);
                        //售卖状态（0 无效，1 有效）当审批状态为通过时才会有售卖状态1
                        shipProduct.setSellStatus(ShipConstants.VALID);
                        //上架设置默认为不上架
                        shipProduct.setShelvesStatus(ShipConstants.SHELVES);
                        //默认不推荐 让工作人员手动去推荐
                        shipProduct.setIsDeleted(ShipConstants.UN_RECOMMENDED);
                        //打包状态
                        shipProduct.setPackStatus(shipInitializationSettings.getPackStatus());
                        shipProduct.setGmtCreate(LocalDateTime.now());
                        shipProduct.setIsDeleted(ShipConstants.NOT_DELETE);
                        shipProduct.setChargeUserId(chargeUserId);
                        shipProductMapper.insert(shipProduct);
                        /**创建默认的成本*/
                        ShipProductCost shipProductCost = new ShipProductCost();
                        Long shipProductCostId = SnowflakeIdWorker.nextId();
                        shipProductCost.setId(shipProductCostId);
                        //关联船票
                        shipProductCost.setShipProductId(productId);
                        shipProductCost.setCostName("默认API成本");
                        shipProductCost.setCurrencyName("HKD");
                        shipProductCost.setCreateId(chargeUserId);
                        shipProductCost.setIsDeleted(ShipConstants.NOT_DELETE);
                        shipProductCost.setGmtCreate(LocalDateTime.now());
                        shipProductCostMapper.insert(shipProductCost);
                        /**保存设置成本价*/
                        System.out.println(rowMap.get("PRICE3"));
                        if (null != rowMap.get("PRICE1") && !"null".equalsIgnoreCase(rowMap.get("PRICE1"))) {
                            saveShipProductCostTourist(shipProductCostId, 1, "成人", new BigDecimal(rowMap.get("PRICE1").toString()), rowMap.get("DETAIL1"), chargeUserId);
                        }
                        if (null != rowMap.get("PRICE2") && !"null".equalsIgnoreCase(rowMap.get("PRICE2"))) {
                            saveShipProductCostTourist(shipProductCostId, 2, "小童", new BigDecimal(rowMap.get("PRICE2").toString()), rowMap.get("DETAIL2"), chargeUserId);
                        }
                        if (null != rowMap.get("PRICE3") && !"null".equalsIgnoreCase(rowMap.get("PRICE3"))) {
                            saveShipProductCostTourist(shipProductCostId, 3, "长者", new BigDecimal(rowMap.get("PRICE3").toString()), rowMap.get("DETAIL3"), chargeUserId);
                        }
                        /**保存成本有效日期集合*/
                        ShipProductCostDate shipProductCostDate = new ShipProductCostDate();
                        shipProductCostDate.setId(SnowflakeIdWorker.nextId());
                        //关联成本ID
                        shipProductCostDate.setCostId(shipProductCostId);
                        shipProductCostDate.setCreateId(chargeUserId);
                        shipProductCostDate.setDateBegin(LocalDateTime.now());
                        shipProductCostDate.setDateEnd(LocalDateTime.now().plusDays(1));
                        shipProductCostDate.setIsDeleted(ShipConstants.NOT_DELETE);
                        shipProductCostDate.setGmtCreate(LocalDateTime.now());
                        shipProductCostDateMapper.insert(shipProductCostDate);
                        //保存产品预售设置
                        ShipProductReservationSettings shipProductReservationSettings = new ShipProductReservationSettings();
                        shipProductReservationSettings.setShipProductId(productId);
                        shipProductReservationSettings.setSaleType(1);
                        shipProductReservationSettings.setIsConfirm(1);
                        shipProductReservationSettings.setServiceChargeType(shipInitializationSettings.getBookingPriceType());
                        shipProductReservationSettings.setServiceChargePrice(shipInitializationSettings.getBookingPrice());
                        shipProductReservationSettings.setRefundFeeType(shipInitializationSettings.getRefundFeePriceType());
                        shipProductReservationSettings.setRefundFeePrice(shipInitializationSettings.getRefundFeePrice());
                        shipProductReservationSettings.setCreateId(chargeUserId);
                        shipProductReservationSettings.setGmtCreate(LocalDateTime.now());
                        shipProductReservationSettings.setIsDeleted(ShipConstants.NOT_DELETE);
                        shipProductReservationSettingsMapper.insert(shipProductReservationSettings);
                    }
                    System.out.println(map);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return stringObjectMap;
    }


    /**
     * 保存旅客设置
     * @param costId
     * @param touristTypeId
     * @param touristTypeName
     * @param costPrice
     * @param costCode
     * @param chargeUserId
     */
    private void saveShipProductCostTourist(Long costId, int touristTypeId, String touristTypeName, BigDecimal costPrice, String costCode, Long chargeUserId) {
        ShipProductCostTourist shipProductCostTourist = new ShipProductCostTourist();
        //关联成本ID
        shipProductCostTourist.setId(SnowflakeIdWorker.nextId());
        shipProductCostTourist.setCostId(costId);
        shipProductCostTourist.setTouristTypeId(Long.valueOf(touristTypeId));
        shipProductCostTourist.setTouristTypeName(touristTypeName);
        shipProductCostTourist.setCostPrice(costPrice);
        shipProductCostTourist.setCostCode(costCode);
        shipProductCostTourist.setGmtCreate(LocalDateTime.now());
        shipProductCostTourist.setIsDeleted(ShipConstants.NOT_DELETE);
        shipProductCostTourist.setCreateId(chargeUserId);
        shipProductCostTouristMapper.insert(shipProductCostTourist);
    }

    /**
     * 确认提交接口
     * @param id
     * @param orderId
     * @return
     */
    @Override
    public Result confirmBookingRn(String id, String orderId) {
        String msgcode = "";
        Map getShippingLineResponse = null;
        try {
            String headXml = "<ns2:confirmBookingRn xmlns:ns2=\"http://ws.service.gen.cks.com/\"> <confirmRnXml>";
            //PAYMENT = 0.月结/现金/point (默认)
            String bodyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CONFIRMINFO>";
            bodyXml += "<TRANSACTION_ID>" + id + "</TRANSACTION_ID> " +
                    "<REFNO>" + orderId + "</REFNO>" +
                    "<PAYMENT>0</PAYMENT> " +
                    "<REMARK></REMARK>";
            bodyXml += "</CONFIRMINFO>";
            String s1 = StringEscapeUtils.escapeXml(bodyXml);
            String s = requestZJInterface(headXml + s1 + "</confirmRnXml></ns2:confirmBookingRn>");
            Map<String, Object> stringObjectMap = ParseXmlUtil.parseXml(s);
            Map Envelope = (Map) stringObjectMap.get("Envelope");
            Map Body = (Map) Envelope.get("Body");
            getShippingLineResponse = (Map) Body.get("confirmBookingRnResponse");
            String returnMap = (String) getShippingLineResponse.get("return");
            Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
            Map table = (Map) stringObjectMap1.get("TABLE");
            List<Map<String,String>> rowList = (List<Map<String,String>>) table.get("ROW");
            if(null != rowList || rowList.size() >0){
                msgcode = "1";
            }
        } catch (Exception e) {
            msgcode = "2";
            log.error("confirmBookingRn-error=>"+getShippingLineResponse);
        }
        return Result.success(msgcode);
    }

    /**
     * 退票接口
     * @param id
     * @return
     */
    @Override
    public Result releaseTicket(String id) {
        Map<String, Object> stringObjectMap = new HashMap<>();
        String msgcode = "";
        Map getShippingLineResponse = null;
        try {
            String headXml = "<ns2:releaseTicket xmlns:ns2=\"http://ws.service.gen.cks.com/\"> <ticketXML>";
            String bodyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><TICKETSINFO VERSION=\"1.0\">";
            bodyXml += "<TRANSACTION_ID>" + id + "</TRANSACTION_ID>";
            bodyXml += "</TICKETSINFO>";
            String s1 = StringEscapeUtils.escapeXml(bodyXml);
            String s = requestZJInterface(headXml + s1 + "</ticketXML></ns2:releaseTicket>");
            stringObjectMap = ParseXmlUtil.parseXml(s);
            Map Envelope = (Map) stringObjectMap.get("Envelope");
            Map Body = (Map) Envelope.get("Body");
            getShippingLineResponse = (Map) Body.get("releaseTicketResponse");
            String returnMap = (String) getShippingLineResponse.get("return");
            Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
            Map table = (Map) stringObjectMap1.get("RESULTINFO");
            msgcode = table.get("MSGCODE").toString();
        } catch (Exception e) {
            msgcode = "2";
            log.error("releaseTicket-error=>"+getShippingLineResponse);
        }
        return Result.success(msgcode);
    }

    /**
     * 提交预订座位
     * @param shipZJProductApiSubmitReq
     * @return
     */
    private List<Map<String, Object>> submitBooking(ShipZJProductApiSubmitReq shipZJProductApiSubmitReq) {
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("MSGCODE", "2");
        stringObjectMap.put("MSGINFO", "");
        List<Map<String, Object>> resultList = new ArrayList<>();
        try {
            String headXml = "<ns2:submitBookingRn xmlns:ns2=\"http://ws.service.gen.cks.com/\"> <submitRnXml>";
            String bodyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><TABLE VERSION=\"1.0\">";
            Long systemOrderId = SnowflakeIdWorker.nextId();
            List<ShipZJProductApiSubmitTicketsReq> shipZJProductApiSubmitTickets = shipZJProductApiSubmitReq.getShipZJProductApiSubmitTickets();
            bodyXml += "<NAME>" + shipZJProductApiSubmitReq.getName() + "</NAME>" +
                    "<EMAIL>" + shipZJProductApiSubmitReq.getEmail() + "</EMAIL>" +
                    "<REFNO>" + systemOrderId + "</REFNO>" +
                    "<ISETICKET>0</ISETICKET>" +
                    "<ADDRESS>" + shipZJProductApiSubmitReq.getAddress() + "</ADDRESS>" +
                    "<CARDNUM>" + shipZJProductApiSubmitReq.getCardNum() + "</CARDNUM>" +
                    "<IP>"+IP+"</IP>" +
                    "<PAYMENT>5</PAYMENT >" +
                    "<LANG>C</LANG><TICKETSINFO>"
            ;
            for (ShipZJProductApiSubmitTicketsReq shipZJProductApiSubmitTicket : shipZJProductApiSubmitTickets) {
                bodyXml += " <ROW>" +
                        "<SEATRANK_ID>" + shipZJProductApiSubmitTicket.getSeatRankId() + "</SEATRANK_ID>" +
                        "<PRICE>" + shipZJProductApiSubmitTicket.getPrice() + "</PRICE>" +
                        "<DETAILID>" + shipZJProductApiSubmitTicket.getTicketCode() + "</DETAILID>" +
                        "<VOYAGEROUTEID>" + shipZJProductApiSubmitTicket.getVoyage() + "</VOYAGEROUTEID>" +
                        "<CLIENTTYPE>" + shipZJProductApiSubmitTicket.getTouristTypeId() + "</CLIENTTYPE>" +
                        "<REALNAMEINFO>" +
                        "<NAME>" + shipZJProductApiSubmitTicket.getName() + "</NAME>" +
                        "<IDNUMBER>" + shipZJProductApiSubmitTicket.getIdNumber() + "</IDNUMBER>" +
                        "<IDTYPE>" + shipZJProductApiSubmitTicket.getIdType() + "</IDTYPE>" +
                        "</REALNAMEINFO>" +
                        "</ROW>";
            }
            bodyXml += "</TICKETSINFO></TABLE>";
            String s1 = StringEscapeUtils.escapeXml(bodyXml);
            String s = requestZJInterface(headXml + s1 + "</submitRnXml></ns2:submitBookingRn>");
            stringObjectMap = ParseXmlUtil.parseXml(s);
            Map Envelope = (Map) stringObjectMap.get("Envelope");
            Map Body = (Map) Envelope.get("Body");
            Map getShippingLineResponse = (Map) Body.get("submitBookingRnResponse");
            String returnMap = (String) getShippingLineResponse.get("return");
            Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
            Map table = (Map) stringObjectMap1.get("RESULTINFO");
            for (ShipErrorCodeEnum value : ShipErrorCodeEnum.values()) {
                if (value.getCode().equals(table.get("MSGINFO"))) {
                    System.out.println(value.getType());
                    stringObjectMap.put("MSGCODE", value.getCode());
                    stringObjectMap.put("MSGINFO", value.getType());
                    break;
                } else {
                    stringObjectMap.put("MSGCODE", table.get("MSGCODE"));
                    stringObjectMap.put("MSGINFO", table.get("MSGINFO"));
                }
            }
            resultList.add(stringObjectMap);
            Map tickets = (Map) table.get("TICKETS");
            Map<String, Object> ticketMap = null;
            List<Map<String, Object>> ticket = null;
            try {
                ticket = (List) tickets.get("TICKET");
            } catch (Exception e) {
                ticketMap = (Map) tickets.get("TICKET");
            }
            if (null == ticketMap) {
                resultList.addAll(ticket);
            } else {
                resultList.add(ticketMap);
            }
        } catch (Exception e) {
            return resultList;
        }
        return resultList;
    }

    /**
     * 初始化座位信息
     */
    @Override
    public void initializeZJShipProductSeat() {
        Map<String, Object> stringObjectMap = null;
        try {
            String s = requestZJInterface("<ns2:getShiptypeLayerRefInfo xmlns:ns2=\"http://ws.service.gen.cks.com/\"/>");
            stringObjectMap = ParseXmlUtil.parseXml(s);
            Map Envelope = (Map) stringObjectMap.get("Envelope");
            Map Body = (Map) Envelope.get("Body");
            Map getShippingLineResponse = (Map) Body.get("getShiptypeLayerRefInfoResponse");
            String returnMap = (String) getShippingLineResponse.get("return");
            Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
            Map seatInfo = (Map) stringObjectMap1.get("SHIPTYPELAYERREFINFO");
            Map seatInfo1 = (Map) seatInfo.get("SHIPTYPELAYERSET");
            List<Map<String, String>> rowList = (List) seatInfo1.get("SHIPTYPELAYER");
            for (Map<String, String> stringStringMap : rowList) {
                ShipProductSeat shipProductSeat = new ShipProductSeat();
                shipProductSeat.setId(SnowflakeIdWorker.nextId());
                shipProductSeat.setShipTypeId(stringStringMap.get("SHIPTYPEID"));
                shipProductSeat.setShipTypeCode(stringStringMap.get("SHIPTYPECODE"));
                shipProductSeat.setLayerId(stringStringMap.get("LAYERID"));
                shipProductSeat.setLayerCode(stringStringMap.get("LAYERCODE"));
                shipProductSeat.setLayercName(stringStringMap.get("LAYERCNAME"));
                shipProductSeat.setLayertName(stringStringMap.get("LAYERTNAME"));
                shipProductSeat.setLayereName(stringStringMap.get("LAYERENAME"));
                shipProductSeat.setLayerSort(stringStringMap.get("LAYERSORT"));
                shipProductSeat.setSeatRankId(stringStringMap.get("SEATRANKID"));
                shipProductSeat.setSeatRankCode(stringStringMap.get("SEATRANKCODE"));
                shipProductSeat.setSeatRankcName(stringStringMap.get("SEATRANKCNAME"));
                shipProductSeat.setSeatRanktName(stringStringMap.get("SEATRANKTNAME"));
                shipProductSeat.setSeatRankeName(stringStringMap.get("SEATRANKENAME"));
                shipProductSeat.setSeatRankSort(stringStringMap.get("SEATRANKSORT"));
                shipProductSeat.setCreateId(00001L);
                shipProductSeat.setGmtCreate(LocalDateTime.now());
                shipProductSeatMapper.insert(shipProductSeat);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 查询api接口往返信息
     * @param shipZJProductApiReq
     * @return
     */
    @Override
    public List<ShipApiProductTypeListDTO> queryVoyage(ShipZJProductApiReq shipZJProductApiReq) {
        Map<String, Object> stringObjectMap = null;
        List<ShipApiProductTypeListDTO> list = null;
        try {
            String headXml = "<ns2:getVoyage xmlns:ns2=\"http://ws.service.gen.cks.com/\"> <filterXml>";
            String bodyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <TABLE VERSION=\"1.0\">";
            bodyXml += "<ROW>" +
                    "<SAILDATE>" + shipZJProductApiReq.getStartDate() + "</SAILDATE>" +
                    "<SAILDATERETURN>" + shipZJProductApiReq.getBackDate() + "</SAILDATERETURN>" +
                    "<FROMPORTCODE>" + shipZJProductApiReq.getDepPlaceCode() + "</FROMPORTCODE>" +
                    "<TOPORTCODE>" + shipZJProductApiReq.getArrPlaceCode() + "</TOPORTCODE>" +
                    "<FROMPORTCODERETURN>" + shipZJProductApiReq.getBackDepPlaceCode() + "</FROMPORTCODERETURN>" +
                    "<TOPORTCODERETURN>" + shipZJProductApiReq.getBackArrPlaceCode() + "</TOPORTCODERETURN>" +
                    "<CURRENCYCODE>HKD</CURRENCYCODE>" +
                    "<ISROUNDTRIP>1</ISROUNDTRIP>" +
                    "<LANG>T</LANG>" +
                    "</ROW>";
            bodyXml += "</TABLE>";
            String s1 = StringEscapeUtils.escapeXml(bodyXml);
            String s = requestZJInterface(headXml + s1 + "</filterXml></ns2:getVoyage>");
            stringObjectMap = ParseXmlUtil.parseXml(s);
            Map Envelope = (Map) stringObjectMap.get("Envelope");
            Map Body = (Map) Envelope.get("Body");
            Map getShippingLineResponse = (Map) Body.get("getVoyageResponse");
            String returnMap = (String) getShippingLineResponse.get("return");
            Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
            Map dateSet = (Map) stringObjectMap1.get("DATASET");
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            //去拿一下api设置
            QueryWrapper<ShipInitializationSettings> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ShipInitializationSettings::getIsDeleted, ShipConstants.NOT_DELETE);
            ShipInitializationSettings shipInitializationSettings = shipInitializationSettingsMapper.selectOne(queryWrapper);

            //解析xml start
            List<Map<String, Object>> rowOwList = null; //VOYAGE_RETURN
            Map<String, Object> rowOwMap = null;
            try {
                rowOwList = (List) dateSet.get("VOYAGE");
            } catch (Exception e) {
                rowOwMap = (Map<String, Object>) dateSet.get("VOYAGE");
            }
            //構造去程集合
            list = new ArrayList<>();
            //構造去程產品
            List<ShipProductApiListDTO> shipProductApiList = new ArrayList<>();
            ShipApiProductTypeListDTO shipApiProductTypeListDTO = new ShipApiProductTypeListDTO();
            shipApiProductTypeListDTO.setTripType(ShipConstants.SHIP_OW_TRIP_TYPE);
            if (null == rowOwMap) {
                for (Map<String, Object> map : rowOwList) {
                    shipProductApiList.add(assemblyShipProductApiList(map, shipInitializationSettings));
                }
            } else {
                shipProductApiList.add(assemblyShipProductApiList(rowOwMap, shipInitializationSettings));
            }
            shipApiProductTypeListDTO.setShipProductApiDetailList(shipProductApiList);
            list.add(shipApiProductTypeListDTO);

            List<Map<String, Object>> rowRtList = null; //VOYAGE_RETURN
            Map<String, Object> rowRtMap = null;
            try {
                rowRtList = (List) dateSet.get("VOYAGE_RETURN");
            } catch (Exception e) {
                rowRtMap = (Map<String, Object>) dateSet.get("VOYAGE_RETURN");
            }
            //構造返程產品
            shipProductApiList = new ArrayList<>();
            shipApiProductTypeListDTO = new ShipApiProductTypeListDTO();
            shipApiProductTypeListDTO.setTripType(ShipConstants.SHIP_RT_TRIP_TYPE);
            if (null == rowRtMap) {
                for (Map<String, Object> map : rowRtList) {
                    shipProductApiList.add(assemblyShipProductApiList(map, shipInitializationSettings));
                }
            } else {
                shipProductApiList.add(assemblyShipProductApiList(rowRtMap, shipInitializationSettings));
            }
            shipApiProductTypeListDTO.setShipProductApiDetailList(shipProductApiList);
            list.add(shipApiProductTypeListDTO);
            //解析xml end

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询往返api产品
     * @param shipZJProductApiReq
     * @return
     */
    @Override
    public List<ShipApiProductTypeListDTO> queryVoyageShipOWTrip(ShipZJProductApiReq shipZJProductApiReq) {
        Map<String, Object> stringObjectMap = null;
        List<ShipApiProductTypeListDTO> list = null;
        try {
            String headXml = "<ns2:getVoyage xmlns:ns2=\"http://ws.service.gen.cks.com/\"> <filterXml>";
            String bodyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <TABLE VERSION=\"1.0\">";
            bodyXml += "<ROW>" +
                    "<SAILDATE>" + shipZJProductApiReq.getStartDate() + "</SAILDATE>" +
                    "<SAILDATERETURN></SAILDATERETURN>" +
                    "<FROMPORTCODE>" + shipZJProductApiReq.getDepPlaceCode() + "</FROMPORTCODE>" +
                    "<TOPORTCODE>" + shipZJProductApiReq.getArrPlaceCode() + "</TOPORTCODE>" +
                    "<FROMPORTCODERETURN></FROMPORTCODERETURN>" +
                    "<TOPORTCODERETURN></TOPORTCODERETURN>" +
                    "<CURRENCYCODE>HKD</CURRENCYCODE>" +
                    "<ISROUNDTRIP>0</ISROUNDTRIP>" +
                    "<LANG>T</LANG>" +
                    "</ROW>";
            bodyXml += "</TABLE>";
            String s1 = StringEscapeUtils.escapeXml(bodyXml);
            String s = requestZJInterface(headXml + s1 + "</filterXml></ns2:getVoyage>");
            stringObjectMap = ParseXmlUtil.parseXml(s);
            Map Envelope = (Map) stringObjectMap.get("Envelope");
            Map Body = (Map) Envelope.get("Body");
            Map getShippingLineResponse = (Map) Body.get("getVoyageResponse");
            String returnMap = (String) getShippingLineResponse.get("return");
            Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
            Map dateSet = (Map) stringObjectMap1.get("DATASET");
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            //去拿一下api设置
            QueryWrapper<ShipInitializationSettings> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ShipInitializationSettings::getIsDeleted, ShipConstants.NOT_DELETE);
            ShipInitializationSettings shipInitializationSettings = shipInitializationSettingsMapper.selectOne(queryWrapper);

            //解析xml start
            List<Map<String, Object>> rowOwList = null; //VOYAGE_RETURN
            Map<String, Object> rowOwMap = null;
            try {
                rowOwList = (List) dateSet.get("VOYAGE");
            } catch (Exception e) {
                rowOwMap = (Map<String, Object>) dateSet.get("VOYAGE");
            }
            //構造去程集合
            list = new ArrayList<>();
            //構造去程產品
            List<ShipProductApiListDTO> shipProductApiList = new ArrayList<>();
            ShipApiProductTypeListDTO shipApiProductTypeListDTO = new ShipApiProductTypeListDTO();
            shipApiProductTypeListDTO.setTripType(ShipConstants.SHIP_OW_TRIP_TYPE);
            if (null == rowOwMap) {
                for (Map<String, Object> map : rowOwList) {
                    shipProductApiList.add(assemblyShipProductApiList(map, shipInitializationSettings));
                }
            } else {
                shipProductApiList.add(assemblyShipProductApiList(rowOwMap, shipInitializationSettings));
            }
            shipApiProductTypeListDTO.setShipProductApiDetailList(shipProductApiList);
            list.add(shipApiProductTypeListDTO);

            //解析xml end

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询单程api产品
     * @param shipZJProductApiReq
     * @return
     */
    public List<ShipProductApiDetailListDTO> queryVoyageShipTrip(ShipZJProductApiReq shipZJProductApiReq) {
        Map<String, Object> stringObjectMap = null;
        List<ShipProductApiDetailListDTO> shipProductApiTouristPriceDTOS = new ArrayList<>();
        try {
            String headXml = "<ns2:getVoyage xmlns:ns2=\"http://ws.service.gen.cks.com/\"> <filterXml>";
            String bodyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <TABLE VERSION=\"1.0\">";
            bodyXml += "<ROW>" +
                    "<SAILDATE>" + shipZJProductApiReq.getStartDate() + "</SAILDATE>" +
                    "<SAILDATERETURN></SAILDATERETURN>" +
                    "<FROMPORTCODE>" + shipZJProductApiReq.getDepPlaceCode() + "</FROMPORTCODE>" +
                    "<TOPORTCODE>" + shipZJProductApiReq.getArrPlaceCode() + "</TOPORTCODE>" +
                    "<FROMPORTCODERETURN></FROMPORTCODERETURN>" +
                    "<TOPORTCODERETURN></TOPORTCODERETURN>" +
                    "<CURRENCYCODE>HKD</CURRENCYCODE>" +
                    "<ISROUNDTRIP>0</ISROUNDTRIP>" +
                    "<LANG>T</LANG>" +
                    "</ROW>";
            bodyXml += "</TABLE>";
            String s1 = StringEscapeUtils.escapeXml(bodyXml);
            String s = requestZJInterface(headXml + s1 + "</filterXml></ns2:getVoyage>");
            stringObjectMap = ParseXmlUtil.parseXml(s);
            Map Envelope = (Map) stringObjectMap.get("Envelope");
            Map Body = (Map) Envelope.get("Body");
            Map getShippingLineResponse = (Map) Body.get("getVoyageResponse");
            String returnMap = (String) getShippingLineResponse.get("return");
            Map<String, Object> stringObjectMap1 = ParseXmlUtil.parseXml(returnMap);
            Map dateSet = (Map) stringObjectMap1.get("DATASET");
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            //去拿一下api设置
            QueryWrapper<ShipInitializationSettings> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ShipInitializationSettings::getIsDeleted, ShipConstants.NOT_DELETE);
            ShipInitializationSettings shipInitializationSettings = shipInitializationSettingsMapper.selectOne(queryWrapper);

            //解析xml start
            List<Map<String, Object>> rowOwList = null; //VOYAGE_RETURN
            Map<String, Object> rowOwMap = null;
            try {
                rowOwList = (List) dateSet.get("VOYAGE");
            } catch (Exception e) {
                rowOwMap = (Map<String, Object>) dateSet.get("VOYAGE");
            }
            //構造去程集合
            //構造去程產品
            ShipApiProductTypeListDTO shipApiProductTypeListDTO = new ShipApiProductTypeListDTO();
            shipApiProductTypeListDTO.setTripType(ShipConstants.SHIP_OW_TRIP_TYPE);
            if (null == rowOwMap) {
                for (Map<String, Object> map : rowOwList) {
                    shipProductApiTouristPriceDTOS.addAll(shipProductApiTouristPriceList(map, shipInitializationSettings));
                }
            } else {
                shipProductApiTouristPriceDTOS = shipProductApiTouristPriceList(rowOwMap, shipInitializationSettings);
            }
            //解析xml end
        } catch (Exception e) {
            e.printStackTrace();
        }
        return shipProductApiTouristPriceDTOS;
    }

    /**
     * 提交座位时校验是否还有库存和价格是否正确
     * @param shipZJProductApiSubmitReq
     * @return
     */
    @Override
    public Result submitShipProduct(ShipZJProductApiSubmitReq shipZJProductApiSubmitReq) {
        ShipZJProductApiReq shipZJProductApiReq = new ShipZJProductApiReq();
        shipZJProductApiReq.setStartDate(shipZJProductApiSubmitReq.getStartDate());
        shipZJProductApiReq.setDepPlaceCode(shipZJProductApiSubmitReq.getDepPlaceCode());
        shipZJProductApiReq.setArrPlaceCode(shipZJProductApiSubmitReq.getArrPlaceCode());
        List<ShipProductApiDetailListDTO> shipProductApiDetailListDTOS = queryVoyageShipTrip(shipZJProductApiReq);
        //判斷是否有該種類的票據
        boolean ticketFlag = false;
        //判斷是否有該航線
        boolean voyageFlag = false;
        //判斷是否有該航線
        boolean dailyStockFlag = false;
        for (ShipZJProductApiSubmitTicketsReq shipZJProductApiSubmitTicket : shipZJProductApiSubmitReq.getShipZJProductApiSubmitTickets()) {
            for (ShipProductApiDetailListDTO shipProductApiDetailListDTO : shipProductApiDetailListDTOS) {
                if (shipZJProductApiSubmitTicket.getVoyage().equals(shipProductApiDetailListDTO.getVoyage())) {
                    for (ShipProductApiTouristPriceDTO shipProductApiTouristPriceDTO : shipProductApiDetailListDTO.getShipProductApiTouristPriceList()) {
                        if (shipZJProductApiSubmitTicket.getTicketCode().equals(shipProductApiTouristPriceDTO.getTicketCode()) &&
                                shipZJProductApiSubmitTicket.getPrice().toString().equals(shipProductApiTouristPriceDTO.getCostPrice().toString()) &&
                                shipZJProductApiSubmitTicket.getSeatRankId().equals(shipProductApiDetailListDTO.getSeatRankId())) {
                            shipProductApiDetailListDTO.setDailyStock(shipProductApiDetailListDTO.getDailyStock() - 1);
                            int dailyStock = shipProductApiDetailListDTO.getDailyStock();
                            if (dailyStock < 0) {
                                dailyStockFlag = true;
                            }
                            ticketFlag = true;
                        }
                    }
                    voyageFlag = true;
                }
            }
        }
        if (!voyageFlag || !ticketFlag) {
            return Result.failed(SystemError.SHIP_PRODUCT_11006);
        }
        if (dailyStockFlag) {
            return Result.failed(SystemError.SHIP_PRODUCT_11024);
        }
        List<Map<String, Object>> maps = submitBooking(shipZJProductApiSubmitReq);
        for (Map<String, Object> map : maps) {
            if (!map.get("MSGCODE").equals("1")) {
                return Result.failed(SystemError.SHIP_PRODUCT_11038);
            }
            break;
        }
        //去保存
        return Result.success(maps);
    }


    /**
     * 计算费用
     * @param price
     * @param shipInitializationSettings
     * @return
     */
    private BigDecimal computePrice(BigDecimal price, ShipInitializationSettings shipInitializationSettings) {
        BigDecimal totalAmount = new BigDecimal("0");
        //判断是加百分比还是加价格
        if (shipInitializationSettings.getBookingPriceType() == ShipConstants.ADJUST_TYPE_PERCENT) {
            double percent = shipInitializationSettings.getBookingPrice();
            percent = percent * 0.01;
            //成本价*百分比+服务费+税费
            totalAmount = totalAmount.add(price.multiply(new BigDecimal(percent)).setScale(0, BigDecimal.ROUND_HALF_UP));
        } else {
            totalAmount = totalAmount.add(new BigDecimal(shipInitializationSettings.getBookingPrice()));
        }
        return price.add(totalAmount);

    }

    /**
     * 组装船票产品信息入库
     * @param map
     * @param shipInitializationSettings
     * @return
     */
    private ShipProductApiListDTO assemblyShipProductApiList(Map<String, Object> map, ShipInitializationSettings shipInitializationSettings) {
        boolean typeFlag = true;
        //構造產品
        ShipProductApiListDTO shipProductApiListDTO = new ShipProductApiListDTO();
        //構造產品詳情
        List<ShipProductApiDetailListDTO> shipProductApiDetailList = new ArrayList<>();
        List<ShipProductApiTouristPriceDTO> shipProductApiTouristPriceList = null;
        Map<String, List> dtseatrankprice = (Map<String, List>) map.get("DTSEATRANKPRICE");
        List<Map<String, String>> rows = dtseatrankprice.get("ROW");
        for (Map<String, String> rowMap : rows) {
            shipProductApiTouristPriceList = new ArrayList<>();
            //每日库存
            int dailyStock = 0;
            if (null != map.get("TICKETNUM")) {
                String[] seatrankids = map.get("TICKETNUM").toString().replace("(", ",").split("\\)");
                for (String seatrankid : seatrankids) {
                    String[] splitStr = seatrankid.split(",");
                    if (splitStr[0].equals(rowMap.get("SEATRANKID"))) {
                        dailyStock = Integer.parseInt(splitStr[1]);
                    }
                }
            }
            if (typeFlag) {
                shipProductApiListDTO.setShipTypeName(map.get("SHIP").toString());
                shipProductApiListDTO.setRouteName(map.get("FROMPORT").toString() + "" + map.get("TOPORT").toString());
                shipProductApiListDTO.setVoyage(null == rowMap.get("VOYAGEROUTEID") ? "" : rowMap.get("VOYAGEROUTEID").toString());
                shipProductApiListDTO.setDepPlaceName(map.get("FROMPORT").toString());
                shipProductApiListDTO.setArrPlaceName(map.get("TOPORT").toString());
                shipProductApiListDTO.setStartTime(map.get("SETOFFTIME").toString());
                shipProductApiListDTO.setCompanyType(ShipCompanyType.ZHUJIANG.getCode());
                if (null != rowMap.get("PRICE1") && !"null".equalsIgnoreCase(rowMap.get("PRICE1"))) {
                    shipProductApiListDTO.setPrice(computePrice(new BigDecimal(rowMap.get("PRICE1").toString()), shipInitializationSettings));
                }
                typeFlag = false;
            }
            ShipProductApiDetailListDTO shipProductApiDetailListDTO = new ShipProductApiDetailListDTO();
            shipProductApiDetailListDTO.setShipTypeName(map.get("SHIP").toString());//船種名稱
            shipProductApiDetailListDTO.setCabinClassStr(rowMap.get("SEATRANK").toString());//座位名稱
            shipProductApiDetailListDTO.setAreaName("亚洲");//地區
            shipProductApiDetailListDTO.setShipCompanyName(shipInitializationSettings.getSupplierName());//供應商名稱
            shipProductApiDetailListDTO.setDailyStock(dailyStock);//餘票
            shipProductApiDetailListDTO.setSeatRankId(rowMap.get("SEATRANKID").toString());
            ShipProductApiTouristPriceDTO shipProductApiTouristPriceDTO1 = new ShipProductApiTouristPriceDTO();
            ShipProductApiTouristPriceDTO shipProductApiTouristPriceDTO2 = new ShipProductApiTouristPriceDTO();
            ShipProductApiTouristPriceDTO shipProductApiTouristPriceDTO3 = new ShipProductApiTouristPriceDTO();
            if (null != rowMap.get("PRICE1") && !"null".equalsIgnoreCase(rowMap.get("PRICE1"))) {
                shipProductApiTouristPriceDTO1.setTouristTypeName("成人");
                shipProductApiTouristPriceDTO1.setPrice(computePrice(new BigDecimal(rowMap.get("PRICE1").toString()), shipInitializationSettings));
                shipProductApiTouristPriceDTO1.setCostPrice(new BigDecimal(rowMap.get("PRICE1").toString()));
                shipProductApiTouristPriceDTO1.setTicketCode(rowMap.get("DETAIL1"));
            }
            if (null != rowMap.get("PRICE2") && !"null".equalsIgnoreCase(rowMap.get("PRICE2"))) {
                shipProductApiTouristPriceDTO2.setTouristTypeName("小童");
                shipProductApiTouristPriceDTO2.setPrice(computePrice(new BigDecimal(rowMap.get("PRICE2").toString()), shipInitializationSettings));
                shipProductApiTouristPriceDTO2.setCostPrice(new BigDecimal(rowMap.get("PRICE2")));
                shipProductApiTouristPriceDTO2.setTicketCode(rowMap.get("DETAIL2"));
            }
            if (null != rowMap.get("PRICE3") && !"null".equalsIgnoreCase(rowMap.get("PRICE3"))) {
                shipProductApiTouristPriceDTO3.setTouristTypeName("長者");
                shipProductApiTouristPriceDTO3.setPrice(computePrice(new BigDecimal(rowMap.get("PRICE3").toString()), shipInitializationSettings));
                shipProductApiTouristPriceDTO3.setCostPrice(new BigDecimal(rowMap.get("PRICE3").toString()));
                shipProductApiTouristPriceDTO3.setTicketCode(rowMap.get("DETAIL3"));
            }
            //組裝旅客類型和價格
            shipProductApiTouristPriceList.add(shipProductApiTouristPriceDTO1);
            shipProductApiTouristPriceList.add(shipProductApiTouristPriceDTO2);
            shipProductApiTouristPriceList.add(shipProductApiTouristPriceDTO3);
            shipProductApiDetailListDTO.setShipProductApiTouristPriceList(shipProductApiTouristPriceList);
            shipProductApiDetailList.add(shipProductApiDetailListDTO);
            shipProductApiListDTO.setShipProductApiDetailList(shipProductApiDetailList);
        }
        return shipProductApiListDTO;
    }

    /**
     * 计算旅客每张票多少钱
     * @param map
     * @param shipInitializationSettings
     * @return
     */
    private List<ShipProductApiDetailListDTO> shipProductApiTouristPriceList(Map<String, Object> map, ShipInitializationSettings shipInitializationSettings) {
        boolean typeFlag = true;
        //構造產品
        ShipProductApiListDTO shipProductApiListDTO = new ShipProductApiListDTO();
        List<ShipProductApiDetailListDTO> list = new ArrayList<>();
        //構造產品詳情
        List<ShipProductApiDetailListDTO> shipProductApiDetailList = new ArrayList<>();
        List<ShipProductApiTouristPriceDTO> shipProductApiTouristPriceList = null;
        Map<String, List> dtseatrankprice = (Map<String, List>) map.get("DTSEATRANKPRICE");
        List<Map<String, String>> rows = dtseatrankprice.get("ROW");
        for (Map<String, String> rowMap : rows) {
            shipProductApiTouristPriceList = new ArrayList<>();
            //每日库存
            int dailyStock = 0;
            if (null != map.get("TICKETNUM")) {
                String[] seatrankids = map.get("TICKETNUM").toString().replace("(", ",").split("\\)");
                for (String seatrankid : seatrankids) {
                    String[] splitStr = seatrankid.split(",");
                    if (splitStr[0].equals(rowMap.get("SEATRANKID"))) {
                        dailyStock = Integer.parseInt(splitStr[1]);
                    }
                }
            }
            if (typeFlag) {
                shipProductApiListDTO.setShipTypeName(map.get("SHIP").toString());
                shipProductApiListDTO.setRouteName(map.get("FROMPORT").toString() + "" + map.get("TOPORT").toString());
                shipProductApiListDTO.setVoyage(null == rowMap.get("VOYAGEROUTEID") ? "" : rowMap.get("VOYAGEROUTEID").toString());
                shipProductApiListDTO.setDepPlaceName(map.get("FROMPORT").toString());
                shipProductApiListDTO.setArrPlaceName(map.get("TOPORT").toString());
                shipProductApiListDTO.setStartTime(map.get("SETOFFTIME").toString());
                shipProductApiListDTO.setCompanyType(ShipCompanyType.ZHUJIANG.getCode());
                if (null != rowMap.get("PRICE1") && !"null".equalsIgnoreCase(rowMap.get("PRICE1"))) {
                    shipProductApiListDTO.setPrice(computePrice(new BigDecimal(rowMap.get("PRICE1").toString()), shipInitializationSettings));
                }
                typeFlag = false;
            }
            ShipProductApiDetailListDTO shipProductApiDetailListDTO = new ShipProductApiDetailListDTO();
            shipProductApiDetailListDTO.setShipTypeName(map.get("SHIP").toString());//船種名稱
            shipProductApiDetailListDTO.setCabinClassStr(rowMap.get("SEATRANK").toString());//座位名稱
            shipProductApiDetailListDTO.setAreaName("亚洲");//地區
            shipProductApiDetailListDTO.setShipCompanyName(shipInitializationSettings.getSupplierName());//供應商名稱
            shipProductApiDetailListDTO.setDailyStock(dailyStock);//餘票
            shipProductApiDetailListDTO.setVoyage(null == rowMap.get("VOYAGEROUTEID") ? "" : rowMap.get("VOYAGEROUTEID").toString());
            shipProductApiDetailListDTO.setSeatRankId(rowMap.get("SEATRANKID").toString());
            ShipProductApiTouristPriceDTO shipProductApiTouristPriceDTO1 = new ShipProductApiTouristPriceDTO();
            ShipProductApiTouristPriceDTO shipProductApiTouristPriceDTO2 = new ShipProductApiTouristPriceDTO();
            ShipProductApiTouristPriceDTO shipProductApiTouristPriceDTO3 = new ShipProductApiTouristPriceDTO();
            if (null != rowMap.get("PRICE1") && !"null".equalsIgnoreCase(rowMap.get("PRICE1"))) {
                shipProductApiTouristPriceDTO1.setTouristTypeName("成人");
                shipProductApiTouristPriceDTO1.setPrice(computePrice(new BigDecimal(rowMap.get("PRICE1").toString()), shipInitializationSettings));
                shipProductApiTouristPriceDTO1.setCostPrice(new BigDecimal(rowMap.get("PRICE1").toString()));
                shipProductApiTouristPriceDTO1.setTicketCode(rowMap.get("DETAIL1"));
            }
            if (null != rowMap.get("PRICE2") && !"null".equalsIgnoreCase(rowMap.get("PRICE2"))) {
                shipProductApiTouristPriceDTO2.setTouristTypeName("小童");
                shipProductApiTouristPriceDTO2.setPrice(computePrice(new BigDecimal(rowMap.get("PRICE2").toString()), shipInitializationSettings));
                shipProductApiTouristPriceDTO2.setCostPrice(new BigDecimal(rowMap.get("PRICE2")));
                shipProductApiTouristPriceDTO2.setTicketCode(rowMap.get("DETAIL2"));
            }
            if (null != rowMap.get("PRICE3") && !"null".equalsIgnoreCase(rowMap.get("PRICE3"))) {
                shipProductApiTouristPriceDTO3.setTouristTypeName("長者");
                shipProductApiTouristPriceDTO3.setPrice(computePrice(new BigDecimal(rowMap.get("PRICE3").toString()), shipInitializationSettings));
                shipProductApiTouristPriceDTO3.setCostPrice(new BigDecimal(rowMap.get("PRICE3").toString()));
                shipProductApiTouristPriceDTO3.setTicketCode(rowMap.get("DETAIL3"));
            }
            //組裝旅客類型和價格
            shipProductApiTouristPriceList.add(shipProductApiTouristPriceDTO1);
            shipProductApiTouristPriceList.add(shipProductApiTouristPriceDTO2);
            shipProductApiTouristPriceList.add(shipProductApiTouristPriceDTO3);
            shipProductApiDetailListDTO.setShipProductApiTouristPriceList(shipProductApiTouristPriceList);
            list.add(shipProductApiDetailListDTO);
        }
        return list;
    }

}
